package com.vehicle.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.vehicle.service.config.SystemConfig;
import com.vehicle.service.config.SystemConfigService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private SystemConfigService systemConfigService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":100009,\"message\":\"未获取token\"}");
            return false;
        }
        try {
            //创建 JWT 签名验证器（指定算法和密钥）
            JWTSigner jwtSigner = JWTSignerUtil.hs256(systemConfigService.get(SystemConfig.jwtSecurityKey).getBytes());
            //创建 JWT 验证器并关联待验证的 token
            JWTValidator jwtValidator = JWTValidator.of(token);
            //验证 JWT 的签名
            jwtValidator.validateAlgorithm(jwtSigner);
            //验证 JWT 的时间有效性
            jwtValidator.validateDate();
            //解析 JWT 并提取用户 ID
            JWT jwt = JWT.of(token);
            request.setAttribute("userId", jwt.getPayload("userId"));
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":100010,\"message\":\"token无效或已过期\"}");
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
